<!--  -->
<template>
  <div class="model-private-detailed common-code-table">
    <div class="header">
      <ul class="header-content-box">
        <li class="middle">
          <h4 class="header-title">{{modelDetailCon.modelName?modelDetailCon.modelName:'--'}}</h4>
          <ul class="header-list">
            <li class="list-item">
              <p class="list-box list-box-top"><span>使用次数</span>{{modelDetailCon.useNum?modelDetailCon.useNum:'0'}}次</p>
            </li>
            <li class="list-item">
              <!-- <p class="list-box list-box-top"><span>大小</span>120MB</p> -->
              <p class="list-box"><span>时间</span>{{modelDetailCon.createTime?new Date(modelDetailCon.createTime).Format("yyyy-MM-dd"):'--'}}</p>
            </li>
            <li class="list-item">
              <p class="list-box"><span>算法框架</span>{{modelDetailCon.framework?modelDetailCon.framework:'--'}}</p>
            </li>
            <li class="list-item">
              <p class="list-box"><span>编程语言</span>{{modelDetailCon.language?modelDetailCon.language:'--'}}</p>
            </li>
          </ul>
        </li>
        <li class="right" :class="{ 'open-model-active-right' : modelOpenType == 1 }">
          <div class="look" @click="lookFun()" :class="{ 'open-model-active' : modelOpenType == 1 }">
            <span v-if="modelOpenType != 1">公开发布</span>
            <span v-else>已发布</span>
          </div>
          <div v-if="modelOpenType != 1" class="delete" @click="deleteModelFun()" :class="{ 'open-model-active' : modelOpenPersonal }">
            删除
          </div>
        </li>
      </ul>
      <ul class="nav-list">
        <li class="main-nav-list nav-left clearfix">
          <ul class="main-nav-list-container">
            <li class="nav-item link-item" :class="{'active': activeTab === 1}" @click="toggleActive(1)">
              基本信息
            </li>
            <li class="nav-item link-item" :class="{'active': activeTab === 2}" @click="toggleActive(2)">
              模型文件
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <div class="content">
      <div v-if="activeTab === 1">
        <div class="basic">
          <div class="basic-title-top">
            <h4 class="left basic-title">模型介绍</h4>
            <div v-if="!basicEditorShow && modelOpenType != 1" class="right" @click="editorFun()">
              <i></i>编辑
            </div>
          </div>
          <p v-if="!basicEditorShow" class="basic-text">{{modelDetailCon.modelIntroduction?modelDetailCon.modelIntroduction:'--'}}</p>
          <div v-if="basicEditorShow" class="basic-editor">
            <el-input
              type="textarea"
              :rows="2"
              class="textmodel-change"
              :class="{'textmodel-change-sele':selectedArea}"
              @focus="selectedArea = true"
              @blur="selectedArea = false"
              placeholder="请输入内容"
              resize='none'
              v-model="modelIntroduction">
            </el-input>
            <div class="basic-editor-bom">
              <el-button type="primary" @click="submitEditorFun()">保存</el-button>
              <el-button class="el-button-cancel" @click="cancelEditorFun()">取消</el-button>
            </div>
          </div>
          <div class="basic-con">
            <h4 class="basic-title">使用该模型的项目</h4>
            <ul class="data-list">
              <li class="item" v-for="(item, index) in openPublicModels" @click="goprojectTaskFun(item.id)" :key="index">
                <div class="item-con">
                  <h4 class="tit">{{item.projectName}}</h4>
                  <p class="text-con">{{item.profile}}</p>
                  <ul class="list-box">
                    <li class="list-item">
                      <i class="icon icon-user"></i>{{item.copyNumber}}个任务
                    </li>
                    <li class="list-item">
                      <i class="icon icon-look"></i>{{item.algorithm}}
                    </li>
                  </ul>
                </div>
              </li>
            </ul>
            <div class="loadmore" v-if="hasNextPageProject">
              <p class="loadmore-box" @click="loadMorePublic">
                <i v-show="loadingMorePublic" class="el-icon-loading"></i>
                <span v-show="!loadingMorePublic">加载更多...</span>
              </p>
            </div>
            <div v-show="openPublicModels.length === 0">
              <div class="no-data-con">
                <!-- <img src="@/common/image/nocontent.png"> -->
                <p class="no-data-title">暂无数据</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="activeTab === 2">
        <div class="table-code-content">
          <div class="filepath-header">
            <div class="filepath-header-left">
              <img class="file-icon" src="@/common/image/icon/folder.png">
              <div class="breadcrumb" v-if="curFilePath === '/'">
                <span class="file-path" @click="clickFilePath('/')">/model/{{modelDetailCon.username}}</span>
              </div>
              <div class="breadcrumb" v-else>
                <span class="file-path" @click="clickFilePath('/')">/model/{{modelDetailCon.username}}</span>
                <span class="file-path" v-for="(item, key) in filePath.slice(1)" :key="key" @click="clickFilePath(item, key)">/{{item}}</span>
              </div>
            </div>
            <div class="filepath-header-right" v-if="modelOpenType != 1">
              <el-button-group v-if="!modelOpenPersonal">
                <el-button size="small"  @click="dialog.createFileFolder=true">新建文件夹</el-button>
                <el-dropdown>
                  <el-button size="small" class="btn-upload">
                    上传
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="clickUploadFile">上传文件</el-dropdown-item>
                    <el-dropdown-item @click.native="clickUploadFolder" v-if="isSupportDir">上传文件夹</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button size="small" @click="_downLoadFile" :disabled="multipleSelection.length === 0">下载</el-button>
                <el-dropdown>
                  <el-button size="small" :disabled="multipleSelection.length === 0">
                    更多...
                  </el-button>
                  <el-dropdown-menu slot="dropdown" >
                    <el-dropdown-item @click.native="clickRename" :disabled="multipleSelection.length !== 1">重命名</el-dropdown-item>
                    <el-dropdown-item @click.native="clickCopy" :disabled="multipleSelection.length < 1">复制</el-dropdown-item>
                    <el-dropdown-item @click.native="deleteFile" :disabled="multipleSelection.length < 1">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-button-group>
              <p v-else>如需修改，请在公开发布中取消对其他用户的公开</p>
            </div>
          </div>
          <div v-show="showEditor === 0">
            <div class="file-table">
              <el-table
                ref="multipleTable"
                :data="fileList"
                style="width: 100%"
                empty-text="暂无文件"
                @selection-change="handleSelectionChange"
                :header-row-class-name="handleTableHeaderclass">
                <el-table-column v-if="modelOpenType != 1" type="selection" width="40"></el-table-column>
                <!-- <el-table-column v-else width="20"></el-table-column> -->
                <el-table-column
                  label="文件/文件夹名称"
                  :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <div class="table-link" @click="clickTableRow(scope.row)">
                      <i :class="{'file-pic': scope.row.isImg, 'file-icon': !scope.row.directory && !scope.row.isImg, 'folder-icon': scope.row.directory}"></i>
                      <span>{{ scope.row.fileName }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="updateTime"
                  label="修改日期"
                  width="200">
                  <template slot-scope="scope">
                    <span>{{ new Date(scope.row.updateTime).Format("yyyy-MM-dd hh:mm:ss") }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="size"
                  label="大小"
                  width="150">
                  <template slot-scope="scope">
                    <span>{{ scope.row.size ? scope.row.size : '--' }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <div class="basePagenate">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :page-size="pageSize"
                  :current-page="pageNumber"
                  :total="totalPage"
                  layout="prev, pager, next">
                </el-pagination>
              </div>
            </div>
            <div class="markdown-box" v-if="showMarkdown">
              <!-- <div class="header-markdown">
                <span class="header-left"><img src="@/common/image/icon/book-open-variant.png">README.md</span>
                <span v-if="!editMarkdown && curDataSet.type !== 1" class="header-right" @click="doEditMarkdown"><i class="icon-edit" />编辑</span>
                <span v-else-if="editMarkdown" class="header-right"><i class="icon-save" /><span @click="doSaveMarkdown">保存</span><i class="icon-cancle" /><span @click="doCancleMarkdown">取消</span></span>
              </div> -->
              <div class="header-editor-box header">
                <div class="header-right">
                  <span class="header-right-edit" v-if="!editMarkdown && curDataSet.type !== 1" @click="doEditMarkdown"><i class="el-icon-edit-outline"></i><span class="">编辑</span></span>
                  <span class="header-right-save" v-else-if="editMarkdown">
                    <el-button class="icon-cancle" @click="doCancleMarkdown">取消</el-button>
                    <el-button class="icon-save" type="primary" @click="doSaveMarkdown">保存</el-button>
                  </span>
                </div>
              </div>
              <viewer
                v-show="!editMarkdown"
                :value="readmeData"
                height="500px"
                class="markdown-content"
              />
              <editor
                v-show="editMarkdown"
                ref="tuiEditor"
                v-model="readmeData"
                :options="editorOptions"
                previewStyle="vertical"
                height="500px"
              />
            </div>
          </div>
        </div>
      </div>
      <!-- 文件编辑查看 -->
      <div v-show="showEditor === 1" class="editor-container">
        <!-- <div class="editor-header">
          <span>{{curEditFile.fileName}}</span>
          <div v-show="showEdit" class="action r action-right"><i class="icon-cancle" /><span class="action-span-hover" @click="doCancle">取消</span></div>
          <div v-show="showEdit" class="action r" @click="doEdit"><span><i class="el-icon-edit-outline"></i><span class="action-span-hover">编辑</span></span></div>
          <div v-show="!showEdit" class="r">
            <span class="action action-right"><i class="icon-save" /><span  class="action-span-hover" @click="doEditSave(0)">保存</span><i class="icon-cancle" /><span class="action-span-hover" @click="doEditCancle">取消</span></span>
          </div>
        </div> -->
        <div class="header-editor-box">
          <span class="header-editor-left-text">{{curEditFile.fileName}}</span>
          <div class="header-right">
            <span class="header-right-edit"  v-if="showEdit" @click="doEdit"><i class="el-icon-edit-outline"></i><span class="">编辑</span></span>
            <span class="header-right-save" v-else-if="!showEdit">
              <el-button class="icon-cancle" @click="doEditCancle">取消</el-button>
              <el-button class="icon-save" type="primary" @click="doEditSave(0)">保存</el-button>
            </span>
          </div>
        </div>
        <div class="code-eidtor">
          <div ref="container" id="container" style="width:100%;height:700px;border:1px solid #ddd"></div>
        </div>
      </div>
      <div v-show="showEditor === 2" class="editor-container">
        <!-- <div class="editor-header">
          <span>{{curEditFile.fileName}}</span>
          <div v-show="!showMDEdit" class="action r action-right"><i class="icon-cancle" /><span class="action-span-hover" @click="doCancle">取消</span></div>
          <div v-show="!showMDEdit" class="action r" @click="doMDEdit"><span><i class="el-icon-edit-outline"></i><span class="action-span-hover">编辑</span></span></div>
          <div v-show="showMDEdit" class="r">
            <span class="action action-right"><i class="icon-save" /><span  class="action-span-hover" @click="doEditSave(1)">保存</span><i class="icon-cancle" /><span class="action-span-hover" @click="doMDEditCancle">取消</span></span>
          </div>
        </div> -->
        <div class="header-editor-box">
          <span class="header-editor-left-text">{{curEditFile.fileName}}</span>
          <div class="header-right">
            <span class="header-right-edit"  v-if="!showMDEdit" @click="doMDEdit"><i class="el-icon-edit-outline"></i><span class="">编辑</span></span>
            <span class="header-right-save" v-else-if="showMDEdit">
              <el-button class="icon-cancle" @click="doMDEditCancle">取消</el-button>
              <el-button class="icon-save" type="primary" @click="doEditSave(1)">保存</el-button>
            </span>
          </div>
        </div>
        <viewer
          v-show="!showMDEdit"
          :value="markdownData"
          height="500px"
          class="md-content"
        />
        <editor
          v-show="showMDEdit"
          ref="mdEditor"
          v-model="markdownData"
          :options="editorOptions"
          previewStyle="vertical"
          height="500px"
        />
      </div>
    </div>
    <el-dialog
      title="图片浏览"
      :visible.sync="dialog.picPreview"
      :pos="'center'"
      width="40%">
      <div class="file-panel picPreview">
        <img :src="curPicPreView" />
      </div>
      <!-- <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button @click="dialog.picPreview=false" class="dialog-button active last">关 闭</button>
        </div>
      </div> -->
    </el-dialog>
    <!-- 创建文件夹 -->
    <el-dialog
      title="创建文件夹"
      :visible.sync="dialog.createFileFolder"
      :pos="'center'"
      :width="'440px'"
      @close="resetForm('cffForm')">
      <el-form :model="createFileFolderForm" :rules="rulesCreateFolder" ref="cffForm" @submit.native.prevent>
        <el-form-item label="文件夹名称：" :label-width="'120px'" prop="name">
          <el-input @keyup.enter.native="submitForm('cffForm')" v-model="createFileFolderForm.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button type="primary" @click="submitForm('cffForm')" class="dialog-button lan">确 定</button>
          <button @click="dialog.createFileFolder=false" class="dialog-button active last">取 消</button>
        </div>
      </div>
    </el-dialog>
    <!-- 重命名 -->
    <el-dialog
      title="重命名"
      :visible.sync="dialog.rename"
      :pos="'center'"
      :width="'440px'"
      @close="resetForm('renameForm')">
      <el-form :model="renameForm" :rules="rulesRename" ref="renameForm" @submit.native.prevent>
        <el-form-item label="名称：" :label-width="'80px'" prop="name">
          <el-input @keyup.enter.native="submitForm('renameForm')" v-model="renameForm.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button type="primary" @click="submitForm('renameForm')" class="dialog-button lan">确 定</button>
          <button @click="dialog.rename=false" class="dialog-button active last">取 消</button>
        </div>
      </div>
    </el-dialog>
    <!-- 上传列表 -->
    <el-dialog
      title="上传列表"
      :visible.sync="dialog.uploadList"
      :close-on-click-modal="false"
      @close="closeUploadDialog"
      :pos="'center'"
      :width="'600px'">
      <div class="file-panel">
        <h2>文件列表</h2>
        <div class="file-list">
          <ul class="file-item" :class="`file-${file.id}`" v-for="(file, index) in uploadFileList" :key="index">
            <li class="file-type"></li>
            <li class="file-name">{{file.name}}</li>
            <li class="file-size">{{fileSize(file.size)}}</li>
            <li class="file-status">待上传</li>
            <li class="progress"></li>
          </ul>
          <div class="no-file" v-if="!uploadFileList.length"><i class="iconfont icon-empty-file"></i> 暂无待上传文件</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button type="primary" @click="startUpload()" class="dialog-button lan">开始上传</button>
          <button @click="cancleUpload" class="dialog-button active last">取 消</button>
        </div>
      </div>
    </el-dialog>
    <!-- 上传文件组件 /gateway/fileCenter/api -->
    <div id="filePicker" class="upload-location">上传文件</div>
    <vue-upload
      ref="uploader"
      uploadButton="#filePicker"
      url="/gateway/fileCenter/api/file/upload?type=4"
      multiple
      :headers="uploadHeader"
      :fileNumLimit="500"
      :fileSingleSizeLimit="fileSingleSize"
      :fileSizeLimit="fileSizeLimit"
      @fileChange="fileChange"
      @uploadStart="onUploadStart"
      @progress="onProgress"
      @completeAll="onAllSuccess"
      @error="onError"
    ></vue-upload>
  </div>
</template>

<script>
import { getModelDetailForCreate, getProjectByModelIdForCreate, updateModelIntro, deleteModel } from '@/api/model'
import { apiGetFileList, apiCreateFileFolder, apiRename, apiCopy, apiDeleteFile } from '@/api/filecenter'
import 'tui-editor/dist/tui-editor.css'
import 'tui-editor/dist/tui-editor-contents.css'
import 'codemirror/lib/codemirror.css'

import { Editor, Viewer } from '@toast-ui/vue-editor'
import vueUpload from '@/base/vue-upload'
import store from '@/store.js'
import qs from 'qs'
import { verifyFileType } from '@/common/js/utils'
import { mapGetters } from 'vuex'
import axios from 'axios'
import * as monaco from 'monaco-editor'
// 文件大小
const WebUploaderObj = window.WebUploader
// 表单校验-name-长度校验
const validateName = (rule, value, callback) => {
  if (value.length > 30) {
    callback(new Error('名称长度须在1到30个字符之间'))
  } else {
    callback()
  }
}
export default {
  components: {
    'editor': Editor,
    'viewer': Viewer,
    vueUpload
  },
  data () {
    return {
      basicEditorShow: false,
      // 文件列表
      fileList: [],
      // 文件路径
      filePath: ['/'],
      // 当前文件路径
      curFilePath: '/',
      // 文件总数
      totalPage: 0,
      // 每页条数
      pageSize: 10,
      // 当前页
      pageNumber: 1,
      selectedArea: false,
      isSupportDir: true,
      // Table选择项
      multipleSelection: [],
      // 上传文件大小限制
      fileSingleSize: 500 * 1024 * 1024,
      // 限制所有文件大小
      fileSizeLimit: 500 * 1024 * 1024,
      // 上传文件列表
      uploadFileList: [],
      // 弹窗显隐
      dialog: {
        picPreview: false,
        createFileFolder: false,
        uploadList: false,
        rename: false
      },
      // 弹窗表单-创建文件夹
      createFileFolderForm: {
        name: ''
      },
      // 弹窗表单-重命名
      renameForm: {
        name: ''
      },
      // 表单验证规则-创建文件夹
      rulesCreateFolder: {
        name: [
          { required: true, message: '请输入文件名称', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ]
      },
      // 表单验证规则-重命名
      rulesRename: {
        name: [
          {
            required: true,
            message: '请输入文件名称',
            trigger: 'blur'
          }, {
            max: 30,
            message: '名称长度须在1到30个字符之间'
          }
        ]
      },
      modelDetailCon: [],
      // 是否有下一页
      hasNextPageProject: false,
      openPublicModels: [],
      modelIntroduction: '',
      modelNameText: '',
      finished: false,
      // 当前页
      pageNumberProject: 1,
      // 每页显示条数
      pageSizeProject: 6,
      bottom: false,
      // 文件内容
      fileContent: '',
      // 文件内容 原始
      fileContentOriginal: '',
      // 显示编辑器
      showEditor: 0,
      // 编辑器显示编辑按钮
      showEdit: true,
      showMDEdit: false,
      // 编辑器是否可编辑
      readOnly: true,
      // 当前编辑文件
      curEditFile: '',
      // 当前浏览图片
      curPicPreView: '',
      editor: '',
      // md文件内容
      markdownData: '',
      // readme文件内容
      readmeData: '',
      // 展示Markdown
      showMarkdown: false,
      // 编辑markdown
      editMarkdown: false,
      editorOptions: {
        hideModeSwitch: true
      },
      modelOpenType: '',
      modelOpenPersonal: false
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    // 当前激活Tab页
    activeTab: {
      get: function () {
        if (this.$route.query.active) {
          return Number(this.$route.query.active)
        } else {
          return 1
        }
      }
    },
    // WebUploader对象
    uploader () {
      return this.$refs.uploader
    },
    uploadHeader: () => {
      let obj = {
        token: store.state.userInfo.token,
        bitaToken: store.state.userInfo.bitaToken,
        userId: store.state.userInfo.userId
      }
      return obj
    }
  },

  beforeMount () {
    window.addEventListener('scroll', this.handleScroll)
  },

  mounted () {
    this.isSupportDir = this.isInputDirSupported()
    if (this.$route.query.active && Number(this.$route.query.active) === 2) {
      this.toggleActive(2)
      this._getFileContent()
    } else {
      this.toggleActive(1)
    }
    this._getModelDetailForCreate()
  },

  methods: {
    toggleActive (val) {
      this.showEditor = 0
      this.showEdit = true
      if (val === 1) {
        this.openPublicModels = []
        this.pageNumberProject = 1
        this.hasNextPageProject = false
        this.$router.push({ path: '/modellump/privatedetailed', query: { active: 1, modelId: this.$route.query.modelId, modelName: this.$route.query.modelName } })
        this._getProjectByModelIdForCreate()
      } else {
        this.curFilePath = '/' + this.$route.query.modelName
        if (this.curFilePath === '/') {
          this.filePath = ['/']
        } else {
          let arr = this.curFilePath.split('/')
          arr[0] = '/'
          this.filePath = arr
        }
        this.pageNumber = 1
        this._getFileList(this.curFilePath)
        this.$router.push({ path: '/modellump/privatedetailed', query: { active: 2, modelId: this.$route.query.modelId, modelName: this.$route.query.modelName } })
        this._getModelDetailForCreate()
      }
    },
    goprojectTaskFun (agm) {
      this.$router.push({ path: '/project/detail/task', query: { projectid: agm } })
    },
    // 公开发布
    lookFun () {
      if (this.modelOpenType !== 1) {
        this.$router.push({ path: '/modellump/modelopen', query: { active: 1, modelId: this.$route.query.modelId, modelNameText: this.modelNameText, modelOpenPersonal: this.modelOpenPersonal } })
      }
    },
    // 删除模型
    deleteModelFun () {
      if (!this.modelOpenPersonal) {
        this.$confirm('确定删除该模型?', '消息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this._deleteModel()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // 编辑
    editorFun () {
      this.basicEditorShow = true
    },
    // 取消编辑
    cancelEditorFun () {
      this.basicEditorShow = false
    },
    // 确定修改简介
    submitEditorFun () {
      this._updateModelIntro()
    },
    // 点击编辑
    doEdit () {
      this.showEdit = false
      this.editor.updateOptions({ readOnly: false })
    },
    doMDEdit () {
      this.showMDEdit = true
      this.$nextTick(() => {
        this.$refs.mdEditor.invoke('setValue', this.markdownData)
        this.$refs.mdEditor.invoke('scrollTop', 1)
      })
    },
    doCancle () {
      this.showEditor = 0
    },
    /*
      description:点击编辑保存
      type: 0 -> tui编辑器保存；1 -> markdown编辑器保存
    */
    doEditSave (type = 0) {
      let blob = ''
      if (type === 0) {
        blob = new Blob([this.editor.getValue()], { type: 'application/octet-stream' })
      } else {
        blob = new Blob([this.$refs.mdEditor.invoke('getValue')], { type: 'text/plain' })
      }
      let fd = new FormData()
      fd.append('dir', this.curFilePath)
      fd.append('name', this.curEditFile.fileName)
      fd.append('type', 4)
      fd.append('file', blob, this.curEditFile.fileName)
      let url = `/gateway/fileCenter/api/file/upload`
      axios({
        method: 'post',
        url: url,
        data: fd
      }).then(res => {
        this.$message({ message: '保存成功', showClose: true, type: 'success' })
        this.showEditor = 0
        this.showMDEdit = false
        this._getFileList(this.curFilePath)
        if (type === 1) {
          this._getFileContent()
        }
      })
    },
    // 点击编辑取消
    doEditCancle () {
      this.editor.setValue(this.fileContentOriginal)
      this.showEdit = true
      this.editor.updateOptions({ readOnly: true })
    },
    doMDEditCancle () {
      this.$refs.mdEditor.invoke('setValue', this.fileContentOriginal)
      this.showMDEdit = false
    },
    // 编辑markdown
    doEditMarkdown () {
      this.editMarkdown = true
      this.$nextTick(() => {
        this.$refs.tuiEditor.invoke('setValue', this.readmeData)
        this.$refs.tuiEditor.invoke('scrollTop', 1)
      })
    },
    // 保存markdown
    doSaveMarkdown () {
      let blob = new Blob([this.$refs.tuiEditor.invoke('getValue')], { type: 'text/plain' })
      let fd = new FormData()
      // let projetName = this.curFilePath.split('projects/')[1].split('/')[0]
      fd.append('dir', `/${this.curProject.projectName}/code`)
      fd.append('type', 4)
      fd.append('name', 'README.md')
      fd.append('file', blob, 'README.md')
      let url = `/gateway/fileCenter/api/file/upload`
      axios({
        method: 'post',
        url: url,
        data: fd
      }).then(res => {
        this.$message({ message: '保存成功', showClose: true, type: 'success' })
        this.editMarkdown = false
        this._getFileContent()
      })
    },
    // 取消编辑markdown
    doCancleMarkdown () {
      this.editMarkdown = false
      this.$nextTick(() => {
        this.$refs.tuiEditor.invoke('setValue', this.fileContentOriginal)
        this.$refs.tuiEditor.invoke('scrollTop', 1)
      })
    },
    // 点击文件路径
    clickFilePath (val, key) {
      this.pageNumber = 1
      if (val === '/') {
        return false
      } else {
        if (val === '/') {
          this.curFilePath = '/'
          this.filePath = ['/']
          this._getFileList('/')
        } else {
          let path = ''
          let pathArr = this.filePath.slice(0, key + 2)
          this.filePath = pathArr
          pathArr.map((item, index) => {
            if (index === 0) {
              path = item
            } else if (index === 1) {
              path = path + item
            } else {
              path = `${path}/${item}`
            }
          })
          this.curFilePath = path
          this._getFileList(path)
        }
      }
    },
    // 点击Table列
    clickTableRow (row) {
      if (row.directory) {
        this.goToFolder(row.fileName)
        this.showEditor = 0
      } else if (row.isImg) {
        this.dialog.picPreview = true
        this._previewImg(row).then(res => {
          this.curPicPreView = URL.createObjectURL(res)
        })
      } else {
        let fileType = row.fileName.replace(/.+\./, '')
        if (fileType === 'md') {
          this.curEditFile = row
          this.fileContent = ''
          this._getFileContent(row.fileName, true)
          this.showEditor = 2
        } else if (verifyFileType(fileType)) {
          this.curEditFile = row
          this.fileContent = ''
          this._getFileContent(row.fileName)
          this.showEditor = 1
        } else {
          this.$message({ message: '暂不支持该文件类型预览', showClose: true, type: 'warning' })
        }
      }
    },
    // 点击文件夹
    goToFolder (dir) {
      this.pageNumber = 1
      if (this.curFilePath === '/') {
        this.curFilePath = `/${dir}`
      } else {
        this.curFilePath = `${this.curFilePath}/${dir}`
      }
      this.filePath.push(dir)
      this._getFileList(this.curFilePath)
    },
    // 分页
    handleSizeChange (val) {
      this.pageSize = val
      this.pageNumber = 1
      this._getFileList(this.curFilePath)
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      this._getFileList(this.curFilePath)
    },
    // 浏览器检测input是否具有webkitdirectory属性
    isInputDirSupported () {
      let tmpInput = document.createElement('input')
      if ('webkitdirectory' in tmpInput || 'mozdirectory' in tmpInput || 'odirectory' in tmpInput || 'msdirectory' in tmpInput || 'directory' in tmpInput) {
        return true
      } else {
        return false
      }
    },
    // Table多选操作
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 点击重命名
    clickRename () {
      this.dialog.rename = true
      this.renameForm.name = this.multipleSelection[0].fileName
    },
    // 点击复制
    clickCopy () {
      this._copy()
    },
    // 删除文件或文件夹
    deleteFile (name) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._deleteFile(name)
      })
    },
    // 获取文件大小
    fileSize (size) {
      return WebUploaderObj.Base.formatSize(size)
    },
    // 开始上传
    startUpload () {
      this.resume()
    },
    fileChange (file) {
      if (!this.flag) {
        this.dialog.uploadList = true
        this.uploadFileList.push(file)
      }
    },
    // 上传错误
    onError (msg) {
      this.uploader.reset()
      this.dialog.uploadList = false
      this.flag = true
      this.$message({ message: msg, showClose: true, type: 'warning' })
    },
    cancleUpload () {
      this.dialog.uploadList = false
      this.uploader.reset()
    },
    closeUploadDialog () {
      this.uploader.reset()
    },
    onUploadStart (file) {
      let dir = ''
      let source = file.source.source
      if (source.webkitRelativePath) {
        let separator = this.curFilePath === '/' ? '' : '/'
        dir = this.curFilePath + separator + source.webkitRelativePath.slice(0, source.webkitRelativePath.lastIndexOf('/' + source.name))
      } else {
        dir = this.curFilePath
      }
      let formData = {
        'dir': dir,
        'userId': this.userInfo.userId,
        'name': source.name
      }
      this.uploader.uploader.options.formData = formData
    },
    onProgress (file, percent) {
      $(`.file-${file.id} .progress`).css('width', percent * 100 + '%')
      $(`.file-${file.id} .file-status`).html((percent * 100).toFixed(2) + '%')
    },
    onSuccess (file, response) {
      this.dialog.uploadList = false
      this._getFileList(this.curFilePath)
    },
    onAllSuccess () {
      this.dialog.uploadList = false
      this._getFileList(this.curFilePath)
      // this._getFileContent()
    },
    resume (file) {
      this.uploader.upload(file)
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 表单提交(cffForm：创建文件夹;renameForm：重命名)
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (formName === 'cffForm') {
            this._createFileFolder()
            this.dialog.createFileFolder = false
          } else if (formName === 'renameForm') {
            this._rename()
            this.dialog.rename = false
          }
          this.resetForm(formName)
        } else {
          return false
        }
      })
    },
    // 点击上传文件-选择文件
    clickUploadFile () {
      this.uploader.reset()
      this.flag = false
      this.uploadFileList = []
      document.getElementById('filePicker').getElementsByTagName('input')[0].removeAttribute('webkitdirectory')
      document.getElementById('filePicker').getElementsByTagName('label')[0].click()
    },
    // 点击上传文件-选择文件夹
    clickUploadFolder () {
      this.uploader.reset()
      this.flag = false
      this.uploadFileList = []
      document.getElementById('filePicker').getElementsByTagName('input')[0].setAttribute('webkitdirectory', '')
      document.getElementById('filePicker').getElementsByTagName('label')[0].click()
    },
    // 处理滚动事件
    handleScroll () {
      let footerHeight = document.getElementById('footer').clientHeight
      let scrollY = window.scrollY
      let visible = document.documentElement.clientHeight
      let pageHeight = document.documentElement.scrollHeight - (footerHeight / 2)
      let bottomOfPage = visible + scrollY >= pageHeight
      this.bottom = bottomOfPage || pageHeight < visible
    },
    loadMorePublic () {
      this.loadingMorePublic = true
      this.pageNumberProject++
      this._getProjectByModelIdForCreate()
    },
    handleTableHeaderclass () {
      return 'table-head-th'
    },
    /*
      -----接口调用-----
    */
    // 查询文件列表
    _getFileList (path) {
      let para = `?type=4&dir=${path}&pageNumber=${this.pageNumber}&pageSize=${this.pageSize}`
      apiGetFileList(para).then(res => {
        if (res.message.code === 0) {
          this.totalPage = res.data.totalCount
          this.fileList = res.data.fileList
          // 判断是否是图片
          let imgExt = ['.png', '.jpg', '.jpeg', '.bmp', '.gif']
          if (this.fileList) {
            this.fileList.forEach(el => {
              let isImg = imgExt.contain(el.fileName.extension())
              el.isImg = isImg
              if (isImg) {
                let preOpt = {}
                let separator = this.curFilePath === '/' ? '' : '/'
                preOpt.src = `/gateway/fileCenter/api/file/preview?type=1&path=${this.curFilePath + separator + el.fileName}`
                el.preOpt = preOpt
              }
            })
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
        this.clickFileBtn = true
      })
    },
    _getModelDetailForCreate () {
      let query = ''
      query = `?modelId=${this.$route.query.modelId}`
      getModelDetailForCreate(query).then(res => {
        if (res.message && res.message.code === 0) {
          this.modelDetailCon = res.data
          this.modelOpenType = res.data.type
          this.modelOpenPersonal = res.data.personal
          this.modelIntroduction = res.data.modelIntroduction
          this.modelNameText = res.data.modelName
        } else {
          return false
        }
      })
    },
    // 我的模型详情项目列表
    _getProjectByModelIdForCreate () {
      let query = ''
      query = `?pageNumber=${this.pageNumberProject}&pageSize=${this.pageSizeProject}&modelId=${this.$route.query.modelId}`
      this.finished = true
      getProjectByModelIdForCreate(query).then(res => {
        this.loadingMorePublic = false
        if (res.message.code === 0) {
          this.hasNextPageProject = res.data.hasNextPage
          this.openPublicModels = this.openPublicModels.concat(res.data.list)
          // this.openTotalNum = res.data.total
          if (this.hasNextPageProject) {
            this.finished = false
          }
        } else {
          return false
        }
      })
    },
    // 修改模型简介
    _updateModelIntro () {
      let data = qs.stringify({
        id: this.$route.query.modelId,
        introduction: this.modelIntroduction
      })
      updateModelIntro(data).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '修改成功！', showClose: true, type: 'success' })
          this._getModelDetailForCreate()
        } else {
          this.$message({ message: '修改失败,请重试!', showClose: true, type: 'error' })
        }
        this.basicEditorShow = false
      })
    },
    // 删除模型
    _deleteModel () {
      let query = ''
      query = `?modelId=${this.$route.query.modelId}`
      deleteModel(query).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '删除成功', showClose: true, type: 'success' })
          this.$router.push({ path: '/modellump', query: { active: 2 } })
        } else {
          this.$message({ message: '删除失败', showClose: true, type: 'success' })
        }
      })
    },
    // 创建文件夹
    _createFileFolder () {
      let path = ''
      if (this.curFilePath === '/') {
        path = `/${this.createFileFolderForm.name}`
      } else {
        path = `${this.curFilePath}/${this.createFileFolderForm.name}`
      }
      let para = qs.stringify({
        type: 4,
        dir: path
      })
      apiCreateFileFolder(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '创建文件夹成功', showClose: true, type: 'success' })
          this._getFileList(this.curFilePath)
        } else if (res.message.code === 10000) {
          this.$message({ message: '文件夹已存在，请换个名字试试。', showClose: true, type: 'warning' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 重命名文件或文件夹
    _rename () {
      let para = ''
      let separator = this.curFilePath === '/' ? '' : '/'
      para = `?type=4&dir=${this.curFilePath + separator + this.multipleSelection[0].fileName}&newDir=${this.curFilePath + separator + this.renameForm.name}`
      apiRename(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '重命名成功', showClose: true, type: 'success' })
          this._getFileList(this.curFilePath)
        } else if (res.message.code === 10000) {
          this.$message({ message: '文件或文件夹已存在，请换个名字试试。', showClose: true, type: 'warning' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 复制
    _copy () {
      let dirs = ''
      let separator = this.curFilePath === '/' ? '' : '/'
      this.multipleSelection.map(item => {
        dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
      })
      let para = `?type=4${dirs}`
      apiCopy(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '复制成功', showClose: true, type: 'success' })
          this._getFileList(this.curFilePath)
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 删除文件或文件夹
    _deleteFile (name1) {
      let dirs = ''
      let separator = this.curFilePath === '/' ? '' : '/'
      this.multipleSelection.map(item => {
        dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
      })
      let para = `?type=4&${dirs}`
      apiDeleteFile(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '删除文件成功', showClose: true, type: 'success' })
          this.pageNumber = this.pageNumber - 1
          this._getFileList(this.curFilePath)
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    /*
      description: 下载文件内容
      fileName: 文件名
      isMDFile: 是否markdown类型文件
    */
    _getFileContent (fileName, isMDFile = false) {
      let separator = ''
      let fileUrl = ''
      if (fileName) {
        separator = this.curFilePath === '/' ? '' : '/'
        fileUrl = `/gateway/fileCenter/api/file/preview?type=4&path=${this.curFilePath + separator + fileName}`
      } else {
        fileUrl = `/gateway/fileCenter/api/file/preview?type=4&path=/${this.curProject.projectName}/code/README.md`
      }
      axios({
        method: 'get',
        url: fileUrl
      }).then(res => {
        if (fileName && !isMDFile) {
          this.fileContent = res.data
          this.fileContentOriginal = res.data
          this.$refs.container.innerHTML = ''
          this.editor = monaco.editor.create(document.getElementById('container'), {
            value: '',
            language: 'python',
            readOnly: true
          })
          if (typeof this.fileContent === 'object') {
            this.fileContent = res.request.response
            this.fileContentOriginal = res.request.response
            this.editor.setValue(this.fileContent)
          } else {
            this.editor.setValue(String(this.fileContent))
          }
        } else if (fileName && isMDFile) {
          if (res.data === '') {
            this.showEditor = 0
          } else {
            this.showEditor = 2
            this.markdownData = res.data
            this.fileContentOriginal = res.data
          }
        } else {
          if (res.data === '') {
            this.showMarkdown = false
          } else {
            this.showMarkdown = true
            this.readmeData = res.data
            this.fileContentOriginal = res.data
          }
        }
      })
    },
    // 预览图片
    _previewImg (row) {
      let separator = this.curFilePath === '/' ? '' : '/'
      let fileUrl = `/gateway/fileCenter/api/file/preview?type=4&path=${this.curFilePath + separator + row.fileName}`
      return axios({
        method: 'get',
        url: fileUrl,
        responseType: 'blob',
        emulateJSON: true
      }).then(res => {
        return Promise.resolve(res.data)
      })
    },
    // 下载文件
    _downLoadFile () {
      if (this.multipleSelection.length === 0) {
        return false
      }
      let dirs = ''
      const separator = this.curFilePath === '/' ? '' : '/'
      let fileName = ''
      this.multipleSelection.map((item, index) => {
        if (index === 0) {
          dirs = 'dirs=' + this.curFilePath + separator + item.fileName
        } else {
          dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
        }
      })
      if (this.multipleSelection.length === 1 && !this.multipleSelection[0].directory) {
        fileName = this.multipleSelection[0].fileName
      } else {
        fileName = 'package.zip'
      }
      // /gateway/fileCenter/api
      const fileUrl = `/gateway/fileCenter/api/file/download?type=4&${dirs}`
      axios.get(fileUrl, {
        responseType: 'arraybuffer'
      }).then(res => {
        const fileContent = res.data
        const blob = new Blob([fileContent], { type: 'application/octet-stream' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(blob, fileName)
        } else {
          // 创建新的URL表示指定的File对象或者Blob对象
          const URL = window.URL || window.webkitURL
          const aTag = document.createElement('a')
          aTag.style = 'display: none'
          aTag.download = fileName
          aTag.href = URL.createObjectURL(blob)
          document.body.appendChild(aTag)
          aTag.click()
          document.body.removeChild(aTag)
          URL.revokeObjectURL(blob)
        }
        // 下载完成，清空Table用户选择
        this.multipleSelection = []
        this.$refs.multipleTable.clearSelection()
      })
    }
  },
  watch: {
    bottom: function (bottom) {
      if (this.finished === true) {
        return
      }
      if (bottom) {
        if (this.activeTab === 1) {
          this.loadingMorePublic = true
          this.pageNumberProject++
          this._getProjectByModelIdForCreate()
        } else {
          return false
          // if (this.curSelectedMyDataSet === 0) {
          //   this._getDataSetList()
          // } else {
          //   this._getUserDataSet(this.curSelectedMyDataSet)
          // }
        }
      }
    }
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
  }
}

</script>
<style lang="stylus">
@import "../../common/stylus/common_code_table"
@import "../../common/stylus/header_editor_box"
line-clamp(n)
  word-break break-all
  word-wrap break-word
  overflow hidden
  text-overflow ellipsis
  display -webkit-box
  /*! autoprefixer: off */
  -webkit-box-orient vertical
  /* autoprefixer: on */
  -webkit-line-clamp n
.model-private-detailed
  isplay flex
  flex-flow column
  font-family PingFangSC-Regular
  .header
    background #f4f7f8
    .header-content-box
      display flex
      justify-content space-between
      width 100%
      margin 0 auto
      max-width 1162px
      display flex
      align-items flex-start
      flex-flow row nowrap
      padding-top 30px
      padding-bottom 36px
      .right
        width 170px
        display flex
        justify-content space-between
        .look
          border 1px solid #D1D2D3
          border-radius 4px
          overflow hidden
          text-align center
          line-height 17px
          font-size 12px
          color #4A4A4A
          padding 7px 24px
          background #ffffff
          box-sizing border-box
          cursor pointer
          &:hover
            background transparent
        .delete
          border 1px solid #D1D2D3
          border-radius 4px
          overflow hidden
          text-align center
          line-height 17px
          font-size 12px
          color #4A4A4A
          padding 7px 19px
          box-sizing border-box
          background #ffffff
          cursor pointer
          &:hover
            background transparent
        .open-model-active
          background transparent
          color #A4A5A5
      .open-model-active-right
        width auto
      .middle
        width 862px
        padding-top 6px
        .header-title
          font-size 22px
          line-height 30px
          color #24292E
          margin-bottom 22px
          line-clamp(1)
          font-weight 600
        .header-list
          display flex
          .list-item
            display inline-block
            margin-right 31px
            max-width 250px
            overflow hidden
            .list-box
              font-size 14px
              line-height 20px
              height 20px
              color #001400
              line-clamp(1)
              span
                margin-right 12px
                color #808080
            .list-box-top
              margin-bottom 8px
    .nav-list
      width 100%
      position relative
      margin 0 auto
      max-width 1162px
      display flex
      .main-nav-list
        height 100%
        .main-nav-list-container
          display flex
          height 100%
          align-items flex-end
          .icon
            display inline-block
            width 30px
            height 50px
          .icon-open-ico
            background url(../../common/image/icon-project/data-set--left-ico-no.png) no-repeat center
            background-size 16px 16px
          .icon-my-ico
            background url(../../common/image/icon-project/data-set-two-ico-no.png) no-repeat center
            background-size 16px 16px
          .nav-item
            padding 0 10px
            font-weight 600
            font-size 14px
            display flex
            color #666
            justify-content center
            align-items center
            cursor pointer
            position relative
            margin 0
            >a
              color #666
              text-decoration none
              cursor pointer
            >a:before
              content ''
              position absolute
              top 0
              right 0
              bottom 0
              left 0
          .link-item
            padding 0 38px
            height 44px
        .nav-item.active
          font-weight bold
          color #2d323b
          background #fff
          box-shadow 0 14px 0 -10px #f3c922 inset
          border-radius 5px 5px 0 0
          .icon-open-ico
            background url(../../common/image/icon-project/data-set--left-ico.png) no-repeat center
            background-size 16px 16px
          .icon-my-ico
            background url(../../common/image/icon-project/data-set-two-ico.png) no-repeat center
            background-size 16px 16px
  .content
    width 100%
    margin 0 auto
    max-width 1162px
    .basic
      padding-top 42px
      .basic-title-top
        display flex
        justify-content space-between
        .basic-title
          font-size 16px
          line-height 22px
          color #2D323B
          font-weight 600
        .left
          display inline-block
        .right
          display flex
          width 48px
          align-items center
          font-size 14px
          line-height 14px
          color #4A4A4A
          cursor pointer
          i
            display inline-block
            width 14px
            height 14px
            margin-right 3px
            background url(../../common/image/icon/mirror-editor-ico-gray.png) no-repeat center
            background-size 14px 14px
            img
              width 100%
              height 100%
          &:hover i
            background url(../../common/image/icon/modle-basic-title.png) no-repeat center
            background-size 14px 14px
          &:hover
            color #2196F3
      .basic-text
        font-size 14px
        line-height 20px
        color #57606A
        margin-bottom 34px
        padding-top 16px
        word-wrap break-word
        word-break normal
      .basic-editor
        padding-top 10px
        .textmodel-change
          height 112px
          box-sizing border-box
          .el-textarea__inner
            padding 17px 16px
            color #999999
            border 1px dashed #CCCCCC
            height 100%
        .textmodel-change-sele
          .el-textarea__inner
            border 1px solid #2196F3
        .basic-editor-bom
          width 100%
          overflow hidden
          padding 14px 0 24px
          .el-button
            float right
            padding 5px 16px
            font-size 12px
            line-height 17px
            border-radius 3px
            margin-left 7px
          .el-button-cancel
            &:hover
              background #f4f7f8
              border 1px solid #dcdfe6
              color #606266
      .basic-con
        .basic-title
          font-size 16px
          line-height 22px
          color #2D323B
          font-weight 600
          margin-bottom 16px
        .data-list
          display flex
          flex-wrap wrap
          .item
            width 368px
            // width 100%
            height 153px
            overflow hidden
            transition all 0.2s linear
            margin-bottom 25px
            margin-right 29px
            border 1px solid #E8E8E8
            border-radius 3px
            .item-con
              padding 17px 25px 0
              position relative
              top 0
              left 0
              height 153px
              box-sizing border-box
              .tit
                line-clamp(1)
                font-size 18px
                line-height 23px
                font-weight bold
                color #2D323B
                margin-bottom 8px
              .text-con
                font-size 14px
                line-height 20px
                color #6E6E6E
                margin-bottom 25px
                line-clamp(2)
              .list-box
                display flex
                align-items center
                justify-content space-between
                position absolute
                bottom 23px
                left 0
                width 100%
                padding 0 25px
                .list-item
                  display inline-block
                  display flex
                  align-items center
                  margin-right 8px
                  font-size 12px
                  line-height 17px
                  color #666666
                  .icon
                    margin-right 4px
                    display inline-block
                  .icon-user
                    width 14px
                    height 10px
                    background url(../../common/image/icon/task.png) no-repeat center
                    background-size 14px 10px
                  .icon-look
                    width 15px
                    height 12px
                    background url(../../common/image/icon/icon-algorithm.png) no-repeat center
                    background-size 15px 12px
            &:nth-of-type(3n)
              margin-right 0
            &:hover
              box-shadow 0 0 10px 0 rgba(74,74,74,0.15)
            &:hover .tit
              color #2196F3
  .table-code-content
      padding-top 35px
  .loadmore
    display flex
    align-items center
    justify-content center
    height 50px
    .loadmore-box
      height 40px
      line-height 40px
      font-size 16px
      width 50%
      display flex
      align-items center
      justify-content center
      background #f5f7fa
      cursor pointer
  .no-data-con
    font-size 14px
    color #2D323B
    padding 10px 0
</style>
